<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Operation\Service;

use Admin\Data\Config;
use Doctrine\ORM\EntityManager;
use Operation\Entity\Ad;

class AdManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加广告
     * @param array $data
     * @return Ad
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAd(array $data)
    {
        if(!empty($data['adImage']['tmp_name'])) $data['adBody'] = str_replace(Config::PUBLIC_PATH, '', $data['adImage']['tmp_name']);
        else unset($data['adImage']);

        $ad = new Ad();
        $ad->valuesSet($data);

        $this->entityManager->persist($ad);
        $this->entityManager->flush();

        return $ad;
    }

    /**
     * 编辑广告
     * @param array $data
     * @param Ad $ad
     * @return Ad
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAd(array $data, Ad $ad)
    {
        if(!empty($data['adImage']['tmp_name'])) $data['adBody'] = str_replace(Config::PUBLIC_PATH, '', $data['adImage']['tmp_name']);
        else unset($data['adImage']);

        $ad->valuesSet($data);
        $this->entityManager->flush();

        return $ad;
    }

    /**
     * 删除广告
     * @param Ad $ad
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAd(Ad $ad)
    {
        $this->entityManager->remove($ad);
        $this->entityManager->flush();

        return true;
    }
}